package com.exam.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.exam.component.MemoryUserRecordSpace;
import com.exam.component.XfXhStreamClient;
import com.exam.config.XfXhConfig;
import com.exam.dto.InteractMsg;
import com.exam.dto.MsgDTO;
import com.exam.util.XfXhWebSocketListener;
import okhttp3.WebSocket;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@RestController
public class AIProvideQuestion {
    @Resource
    private XfXhConfig xfXhConfig;

    @Resource
    private XfXhStreamClient xfXhStreamClient;

    @Resource
    private MemoryUserRecordSpace memoryUserRecordSpace;


    @GetMapping("/aiProvideQuestion")
    public String aiProvideQuestion(@RequestParam("id") Long id, @RequestParam("subject") String subject, @RequestParam("type") String type, @RequestParam("question_count") Integer question_count, @RequestParam("score")String score, @RequestParam("extra")String extra) throws InterruptedException {
        String question = "请生成关于"+subject+"的"+type+question_count+"道，"+"每道"+score+"分，需要你返回试卷的名称，试卷内容，每道题的参考答案和分数，不要给我省略内容，我需要直接使用你的文本"+extra;
        if (StrUtil.isBlank(question)) {
            return "无效问题，请重新输入";
        }
        // 尝试锁定用户
        if (!memoryUserRecordSpace.tryLock(id)) {
            return "正在处理上次问题，请稍后再试";
        }
        // 获取连接令牌
        if(!xfXhStreamClient.operateToken(XfXhStreamClient.GET_TOKEN_STATUS)){
            // 释放锁
            memoryUserRecordSpace.unLock(id);
            return "当前大模型连接数过多，请稍后再试";
        }
        MsgDTO msgDTO = MsgDTO.createUserMsg(question);
        XfXhWebSocketListener listener = new XfXhWebSocketListener();
        // 组装上下文内容发送
        List<MsgDTO> msgList = memoryUserRecordSpace.getAllInteractMsg(id);

        msgList.add(msgDTO);
        WebSocket webSocket = xfXhStreamClient.sendMsg(UUID.randomUUID().toString().substring(0, 10), msgList, listener);
        if (webSocket == null) {
            // 归还令牌
            xfXhStreamClient.operateToken(XfXhStreamClient.BACK_TOKEN_STATUS);
            // 释放锁
            memoryUserRecordSpace.unLock(id);
            return "系统内部错误，请联系管理员";
        }
        try {
            int count = 0;
            // 为了避免死循环，设置循环次数来定义超时时长
            int maxCount = xfXhConfig.getMaxResponseTime() * 5;
            while (count <= maxCount) {
                Thread.sleep(200);
                if (listener.isWsCloseFlag()) {
                    break;
                }
                count++;
            }
            if (count > maxCount) {
                return "大模型响应超时，请联系管理员";
            }
            // 将记录添加到 memoryUserRecordSpaces
            String answer = "{\"exam\":\"" + listener.getAnswer().toString() + "\"}";
            memoryUserRecordSpace.storeInteractMsg(id, new InteractMsg(MsgDTO.createUserMsg(question), MsgDTO.createAssistantMsg(answer) ,MsgDTO.createSystemMsg("你是该专业课程的老师")));
//            HttpRequest.post("http://127.0.0.1:5000/"+type)
//                    //body传参方式
//                    .body(answer)
//                    //超时，毫秒
//                    .timeout(20000)
//                    .execute().body();
            return answer;
        } finally {
            // 关闭连接
            webSocket.close(1000, "");
            // 释放锁
            memoryUserRecordSpace.unLock(id);
            // 归还令牌
            xfXhStreamClient.operateToken(XfXhStreamClient.BACK_TOKEN_STATUS);
        }
    }
}
